<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-pic"></i> {{ pageTitle }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.noteId" :placeholder="noteIdPlaceholder" class="handle-input mr10" clearable />
        <el-input v-model="searchForm.noteTitle" :placeholder="noteTitlePlaceholder" class="handle-input mr10"
          clearable />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showAddReply">新增评论</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="replyTable" header-cell-class-name="table-header">
        <el-table-column prop="replyId" label="评论ID" width="120" />
        <el-table-column prop="authorAvatar" label="回复者头像">
          <template #default="scope">
            <el-image v-if="scope.row.avatarUrl" :src="scope.row.avatarUrl"
              style="width:40px;height:40px;border-radius:50%;" fit="cover" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="authorInfo" label="回复者昵称/ID">
          <template #default="scope">
            {{ scope.row.authorName }} / {{ scope.row.authorId }}
          </template>
        </el-table-column>
        <el-table-column prop="parentAuthorAvatar" label="被回复者头像">
          <template #default="scope">
            <el-image v-if="scope.row.parentAuthorAvatar" :src="scope.row.parentAuthorAvatar"
              style="width:40px;height:40px;border-radius:50%;" fit="cover" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="parentAuthorInfo" label="被回复者昵称/ID">
          <template #default="scope">
            <span v-if="scope.row.parentAuthorName">{{ scope.row.parentAuthorName }} / {{ scope.row.parentAuthorId
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="replyContent" label="回复内容">
          <template #default="scope">
            <!-- 优先显示文本内容 -->
            <div v-if="scope.row.replayContent && scope.row.replayContent.trim()" class="content-cell">
              {{ scope.row.replayContent }}
            </div>
            <!-- 没有文本内容时显示图片 -->
            <div v-else-if="scope.row.replayImgUrl" class="image-content">
              <el-image :src="scope.row.replayImgUrl" style="width:60px;height:60px;border-radius:4px;" fit="cover"
                :preview-src-list="[scope.row.replayImgUrl]" />
            </div>
            <!-- 都没有时显示 - -->
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="parentId" label="上级ID">
          <template #default="scope">
            {{ scope.row.parentId || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="topParentId" label="顶层ID">
          <template #default="scope">
            {{ scope.row.topParentId || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="authorReplay" label="是否作者">
          <template #default="scope">
            <el-tag :type="scope.row.authorReplay === 1 ? 'success' : 'info'">
              {{ scope.row.authorReplay === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="replayStatus" label="是否折叠">
          <template #default="scope">
            <el-tag :type="scope.row.replayStatus === 1 ? 'warning' : 'success'">
              {{ scope.row.replayStatus === 1 ? '已折叠' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="upCount" label="点赞数" width="100" align="center">
          <template #default="scope">
            {{ scope.row.upCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ dateFormat(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="text" @click="showEditReply(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新建/编辑评论弹窗 -->
    <el-dialog v-model="addDialog.visible" :title="addDialog.isEdit ? '编辑评论' : '新增评论'" width="60%">
      <el-form :model="addDialog.form" label-width="120px">
        <el-form-item :label="`选择${typePrefix}`" required>
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="noteDisplayText" :placeholder="`请选择${typePrefix}`" readonly style="flex: 1;" />
            <el-button :disable="addDialog.isEdit" @click="selectNote">选择{{ typePrefix }}</el-button>
            <el-button v-if="addDialog.form.selectedNote" type="danger" :disable="addDialog.isEdit"
              @click="clearNote">清除</el-button>
          </div>
        </el-form-item>
        <!-- <el-form-item label="选择回复者" required>
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="authorDisplayText" placeholder="请选择回复者" readonly style="flex: 1;" />
            <el-button @click="selectAuthor">选择回复者</el-button>
            <el-button v-if="addDialog.form.author" type="danger" @click="clearAuthor">清除</el-button>
          </div>
        </el-form-item> -->
        <!-- <el-form-item label="选择回复评论">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="replyDisplayText" placeholder="请选择要回复的评论（可选）" readonly style="flex: 1;" />
            <el-button @click="selectReplyComment" :disabled="!addDialog.form.selectedNote">选择回复评论</el-button>
            <el-button v-if="addDialog.form.selectedReply" type="danger" @click="clearReply">清除</el-button>
          </div>
          <div class="form-tip">选择要回复的评论，如果不选择则为顶级评论</div>
        </el-form-item> -->
        <el-form-item label="回复类型" required>
          <el-radio-group v-model="addDialog.form.replayType">
            <el-radio :label="0">文字</el-radio>
            <el-radio :label="1">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addDialog.form.replayType === 0" label="回复内容" required>
          <el-input v-model="addDialog.form.replayContent" type="textarea" :rows="4" placeholder="请输入回复内容" />
        </el-form-item>
        <el-form-item v-if="addDialog.form.replayType === 1" label="回复图片" required>
          <MediaUploader v-model="addDialog.form.imageList" :limit="1" accept-type="image" />
          <div class="form-tip">请上传一张图片</div>
        </el-form-item>
        <!-- <el-form-item label="评论状态">
          <el-radio-group v-model="addDialog.form.replayStatus">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">已折叠</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="点赞数">
          <el-input-number v-model="addDialog.form.upCount" :min="0" placeholder="点赞数" />
        </el-form-item> -->
        <!-- <el-form-item label="创建时间">
          <el-date-picker v-model="addDialog.form.createTime" type="datetime" placeholder="选择创建时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="addDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addDialog.isEdit ? saveEdit() : saveAdd()">保存</el-button>
      </template>
    </el-dialog>

    <!-- 选择动态/帖子弹窗 -->
    <SelectMoments v-if="replyType === 'blog'" v-model="selectNoteVisible" :selected-data="addDialog.form.selectedNote"
      @confirm="handleSelectNote" />
    <SelectPost v-if="replyType === 'forum'" v-model="selectNoteVisible" :selected-data="addDialog.form.selectedNote"
      @confirm="handleSelectNote" />

    <!-- 选择回复者弹窗 -->
    <SelectUser v-model="selectAuthorVisible" :multiple="false"
      :selected-user-ids="addDialog.form.author ? [addDialog.form.author.userId] : []" @confirm="handleSelectAuthor" />

    <!-- 选择回复评论弹窗 -->
    <SelectReply v-model="selectReplyVisible" :reply-type="replyType"
      :note-id="addDialog.form.selectedNote ? addDialog.form.selectedNote.id : ''"
      :selected-data="addDialog.form.selectedReply" @confirm="handleSelectReply" />
  </div>
</template>

<script>
import moment from "moment";
import MediaUploader from "@/components/mediaUploader.vue";
import SelectUser from "@/components/selectUser.vue";
import SelectMoments from "@/components/selectMoments.vue";
import SelectPost from "@/components/selectPost.vue";
import SelectReply from "@/components/selectReply.vue";
import { getBlogReplies, addBlogReply, deleteBlogReply, updateBlogReply, getForumReplies, addForumReply, deleteForumReply, updateForumReply } from "@/api/content";
import { getIp } from "@/utils/index.js";

export default {
  name: "ReplyList",
  components: {
    MediaUploader,
    SelectUser,
    SelectMoments,
    SelectPost,
    SelectReply
  },
  data() {
    return {
      // 根据路由判断是动态还是帖子
      replyType: 'blog', // 'blog' 或 'forum'
      searchForm: {
        noteId: "",
        noteTitle: "",
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      addDialog: {
        visible: false,
        isEdit: false, // 是否为编辑模式
        editId: null, // 编辑的评论ID
        form: {
          selectedNote: null, // 选中的动态/帖子
          author: null, // 回复者
          selectedReply: null, // 选中的回复评论
          replayType: 0, // 回复类型：0文字，1图片
          replayContent: "", // 回复内容
          imageList: [], // 图片列表
          replayStatus: 0, // 评论状态：0正常，1已折叠
          upCount: 0, // 点赞数
          createTime: "", // 创建时间
          ipAddress: "", // IP地址（不显示）
        },
      },
      // 选择弹窗状态
      selectNoteVisible: false, // 选择动态/帖子
      selectAuthorVisible: false, // 选择回复者
      selectReplyVisible: false, // 选择回复评论
    };
  },
  computed: {
    // 根据类型获取前缀文本（动态/帖子）
    typePrefix() {
      return this.replyType === 'blog' ? '动态' : '帖子';
    },
    // 页面标题
    pageTitle() {
      return `${this.typePrefix}评论列表`;
    },
    // 动态/帖子ID占位符
    noteIdPlaceholder() {
      return `${this.typePrefix}ID`;
    },
    // 动态/帖子标题占位符
    noteTitlePlaceholder() {
      return `${this.typePrefix}标题`;
    },
    // 动态/帖子显示文本
    noteDisplayText() {
      return this.addDialog.form.selectedNote ?
        `${this.addDialog.form.selectedNote.title || '无标题'} (ID: ${this.addDialog.form.selectedNote.id})` :
        '';
    },
    // 回复者显示文本
    authorDisplayText() {
      return this.addDialog.form.author ?
        `${this.addDialog.form.author.nickname} (${this.addDialog.form.author.userId})` :
        '';
    },
    // 回复评论显示文本
    replyDisplayText() {
      return this.addDialog.form.selectedReply ?
        `${this.addDialog.form.selectedReply.replayContent || '图片评论'} (ID: ${this.addDialog.form.selectedReply.replyId})` :
        '';
    }
  },
  mounted() {
    // 根据路由判断是动态还是帖子
    this.replyType = this.$route.path.includes('blogReply') ? 'blog' : 'forum';

    // 如果URL中有noteId参数，自动填充到搜索条件中
    if (this.$route.query.noteId) {
      this.searchForm.noteId = this.$route.query.noteId;
    }

    this.getData();
  },
  watch: {
    'addDialog.form.replayType'() {
      // 切换类型时清空内容
      this.addDialog.form.replayContent = '';
      this.addDialog.form.imageList = [];
    },
    // 监听路由变化
    '$route'(to) {
      // 检查是否在评论列表路由之间切换
      const isBlogRoute = to.path.includes('blogReply');
      const isForumRoute = to.path.includes('forumReply');

      if (isBlogRoute || isForumRoute) {
        // 更新类型
        this.replyType = isBlogRoute ? 'blog' : 'forum';

        // 重置页面数据
        this.resetPageData();

        // 如果URL中有noteId参数，自动填充到搜索条件中
        if (to.query.noteId) {
          this.searchForm.noteId = to.query.noteId;
        }

        // 重新获取数据
        this.getData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    formatDateTime(date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    handleSearch() {
      // 搜索时重置到第一页
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      // 根据搜索表单构建查询参数
      if (this.searchForm.noteId) {
        params.noteId = this.searchForm.noteId;
      }
      if (this.searchForm.noteTitle) {
        params.noteTitle = this.searchForm.noteTitle;
      }

      return params;
    },
    // 获取对应的API方法
    getApiMethods() {
      if (this.replyType === 'blog') {
        return {
          get: getBlogReplies,
          add: addBlogReply,
          update: updateBlogReply,
          delete: deleteBlogReply
        };
      } else {
        return {
          get: getForumReplies,
          add: addForumReply,
          update: updateForumReply,
          delete: deleteForumReply
        };
      }
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const apiMethods = this.getApiMethods();
        const response = await apiMethods.get(params);

        if (response && response.data) {
          // 将API返回的数据映射到表格需要的格式
          this.tableData = response.data.rows.map(item => ({
            replyId: item.replyId || item.id,
            avatarUrl: item.avatarUrl || '',
            authorName: item.authorName || '',
            authorId: item.authorId || '',
            parentAuthorAvatar: item.parentAuthorAvatar || '',
            parentAuthorName: item.parentAuthorName || '',
            parentAuthorId: item.parentAuthorId || '',
            replayContent: item.replayContent || '',
            replayImgUrl: item.replayImgUrl || '',
            replayType: item.replayType || 0,
            authorReplay: item.authorReplay || 0,
            replayStatus: item.replayStatus || 0,
            upCount: item.upCount || 0,
            parentId: item.parentId || '',
            topParentId: item.topParentId || '',
            createTime: item.createTime,
            // 保留原始数据用于编辑
            _original: item
          }));

          // 更新总数（如果接口返回了总数）
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取评论数据失败:', error);
        this.$message.error('获取评论数据失败');
      }
    },
    showAddReply() {
      this.addDialog.visible = true;
      this.addDialog.isEdit = false;
      this.addDialog.editId = null;
      this.addDialog.form = {
        selectedNote: null,
        author: null,
        selectedReply: null,
        replayType: 0,
        replayContent: "",
        imageList: [],
        replayStatus: 0,
        upCount: 0,
        createTime: this.formatDateTime(new Date()),
        ipAddress: "",
      };
      // 获取缓存的IP地址
      this.addDialog.form.ipAddress = getIp();
    },
    async showEditReply(row) {
      this.addDialog.isEdit = true;
      this.addDialog.editId = row.replyId;

      // 填充编辑数据
      const original = row._original;

      // 根据数据判断回复类型：有图片内容则为图片类型，否则为文本类型
      const replayType = original.replayImgUrl ? 1 : 0;

      this.addDialog.form = {
        selectedNote: {
          id: original.noteId,
          title: original.noteTitle || '无标题'
        },
        author: {
          userId: original.authorId,
          nickname: original.authorName,
          userPic: original.avatarUrl || ''
        },
        selectedReply: original.parentId ? {
          replyId: original.parentId,
          replayContent: '已选择回复评论'
        } : null,
        replayType: replayType,
        replayContent: "",
        imageList: [],
        replayStatus: original.replayStatus || 0,
        upCount: original.upCount || 0,
        createTime: original.createTime ? this.formatDateTime(original.createTime) : this.formatDateTime(new Date()),
        ipAddress: getIp(),
      };

      // 等待下一个tick，确保表单重置完成
      await this.$nextTick();

      // 然后设置内容数据
      this.addDialog.form.replayContent = original.replayContent || "";
      this.addDialog.form.imageList = original.replayImgUrl ? [{
        url: original.replayImgUrl,
        type: 'image/jpeg',
        name: 'reply_image.jpg'
      }] : [];

      console.log("editRow", this.addDialog);

      // 再等待一个tick，确保媒体数据设置完成
      await this.$nextTick();

      // 最后显示弹窗
      this.addDialog.visible = true;
    },
    async saveEdit() {
      try {
        // 验证必填项
        if (!this.addDialog.form.selectedNote) {
          this.$message.error(`请选择${this.typePrefix}`);
          return;
        }
        // if (!this.addDialog.form.author) {
        //   this.$message.error('请选择回复者');
        //   return;
        // }
        if (this.addDialog.form.replayType === 0 && !this.addDialog.form.replayContent.trim()) {
          this.$message.error('请输入回复内容');
          return;
        }
        if (this.addDialog.form.replayType === 1 && (!this.addDialog.form.imageList || this.addDialog.form.imageList.length === 0)) {
          this.$message.error('请上传回复图片');
          return;
        }

        // 构建编辑参数
        const params = this.buildReplyParams();
        params.replyId = this.addDialog.editId;
        params.id = this.addDialog.editId;

        const apiMethods = this.getApiMethods();
        await apiMethods.update(params);

        this.$message.success('编辑评论成功');
        this.addDialog.visible = false;
        this.getData();
      } catch (error) {
        console.error('编辑评论失败:', error);
        this.$message.error('编辑评论失败');
      }
    },
    async saveAdd() {
      try {
        // 验证必填项
        if (!this.addDialog.form.selectedNote) {
          this.$message.error(`请选择${this.typePrefix}`);
          return;
        }
        // if (!this.addDialog.form.author) {
        //   this.$message.error('请选择回复者');
        //   return;
        // }
        if (this.addDialog.form.replayType === 0 && !this.addDialog.form.replayContent.trim()) {
          this.$message.error('请输入回复内容');
          return;
        }
        if (this.addDialog.form.replayType === 1 && (!this.addDialog.form.imageList || this.addDialog.form.imageList.length === 0)) {
          this.$message.error('请上传回复图片');
          return;
        }

        // 构建新增参数
        const params = this.buildReplyParams();

        const apiMethods = this.getApiMethods();
        await apiMethods.add(params);

        this.$message.success('新增评论成功');
        this.addDialog.visible = false;
        this.getData();
      } catch (error) {
        console.error('新增评论失败:', error);
        this.$message.error('新增评论失败');
      }
    },
    buildReplyParams() {
      const form = this.addDialog.form;

      return {
        noteId: form.selectedNote.id,
        // noteTitle: form.selectedNote.title,
        // authorId: form.author?.userId,
        // authorName: form.author?.nickname,
        // avatarUrl: form.author?.userPic || '',
        // replayType: form.replayType,
        replayContent: form.replayType === 0 ? form.replayContent : '',
        replayImgUrl: form.replayType === 1 && form.imageList.length > 0 ? form.imageList[0].url : '',
        // replayStatus: form.replayStatus,
        // upCount: form.upCount || 0,
        // parentId: form.selectedReply ? form.selectedReply.replyId : '',
        // topParentId: form.selectedReply ? (form.selectedReply.topParentId || form.selectedReply.replyId) : '',
        // createTime: form.createTime || this.formatDateTime(new Date()),
        ipAddress: form.ipAddress || '',
      };
    },
    handleDelete(row) {
      this.$confirm("确定要删除该评论吗？", "提示", { type: "warning" }).then(async () => {
        try {
          const apiMethods = this.getApiMethods();
          await apiMethods.delete({ replyId: row.replyId, id: row.replyId });

          this.$message.success('删除评论成功');
          this.getData();
        } catch (error) {
          console.error('删除评论失败:', error);
          this.$message.error('删除评论失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
    // 选择动态/帖子
    selectNote() {
      this.selectNoteVisible = true;
    },
    clearNote() {
      this.addDialog.form.selectedNote = null;
      // 清除选中的动态/帖子时，也清除选中的回复评论
      this.addDialog.form.selectedReply = null;
    },
    handleSelectNote(selectedNote) {
      if (selectedNote) {
        this.addDialog.form.selectedNote = selectedNote;
        // 选择新的动态/帖子时，清除之前选中的回复评论
        this.addDialog.form.selectedReply = null;
      }
    },
    // 选择回复者
    selectAuthor() {
      this.selectAuthorVisible = true;
    },
    clearAuthor() {
      this.addDialog.form.author = null;
    },
    handleSelectAuthor(selectedUsers) {
      if (selectedUsers && selectedUsers.length > 0) {
        this.addDialog.form.author = selectedUsers[0];
      }
    },
    // 选择回复评论
    selectReplyComment() {
      if (!this.addDialog.form.selectedNote) {
        this.$message.warning(`请先选择${this.typePrefix}`);
        return;
      }
      this.selectReplyVisible = true;
    },
    clearReply() {
      this.addDialog.form.selectedReply = null;
    },
    handleSelectReply(selectedReply) {
      if (selectedReply) {
        this.addDialog.form.selectedReply = selectedReply;
      }
    },


    // 重置页面数据
    resetPageData() {
      // 重置搜索表单
      this.searchForm = {
        noteId: "",
        noteTitle: "",
      };

      // 重置表格数据
      this.tableData = [];

      // 重置分页
      this.pagination.currentPage = 1;
      this.pagination.total = 0;
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.mb10 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.image-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

:deep(.el-date-editor) {
  margin-right: 10px;
  width: 300px;
}
</style>